<template>
    <a-modal :open="visible" :title="title" width="750px" forceRender :destroyOnClose="true" :maskClosable="false"
        @cancel="onClose">
        <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 4 }">
            <a-form-item label="项目名称" name="blprojectname">
                <a-input :disabled="canEdit" v-model:value="form.blprojectname" placeholder="请输入项目名称" />
            </a-form-item>
            <a-form-item label="项目编号" name="blprojectnum">
                <a-input :disabled="canEdit" v-model:value="form.blprojectnum" placeholder="请输入项目编号" />
            </a-form-item>
            <a-form-item label="执行单位" name="bldepartmentnum">
                <a-select :disabled="canEdit" v-model:value="form.bldepartmentnum" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeDept" :options="options" placeholder="请选择执行单位"></a-select>
            </a-form-item>
            <a-form-item label="项目联系人" name="blprojectcontact">
                <a-select :disabled="canEdit" v-model:value="form.blprojectcontact" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeContact" :options="optionsContact"
                    placeholder="请选择项目联系人"></a-select>
            </a-form-item>
            <a-form-item label="项目负责人" name="blprojectleader">
                <a-select :disabled="canEdit" v-model:value="form.blprojectleader" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeLeader" :options="optionsLeader"
                    placeholder="请选择项目负责人"></a-select>
            </a-form-item>
            <a-form-item label="财务编号" name="blfinancialnum">
                <a-input :disabled="canEdit" v-model:value="form.blfinancialnum" placeholder="请输入财务编号" />
            </a-form-item>
            <a-form-item label="项目状态" name="blprojectstatus">
                <a-select :disabled="canEdit" v-model:value="form.blprojectstatus" style="width: 100%"
                    placeholder="请选择项目状态" :allowClear="true" size="Middle" @change="changeProStatus">
                    <a-select-option value="0">无</a-select-option>
                    <a-select-option value="1">未执行</a-select-option>
                    <a-select-option value="2">执行中</a-select-option>
                    <a-select-option value="3">待续约</a-select-option>
                    <a-select-option value="4">结项</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="项目成立日期" name="blregist">
                <a-date-picker :disabled="canEdit" :valueFormat="'YYYY-MM-DD'" ; style="width: 100%;"
                    placeholder="请选择项目成立日期" v-model:value="form.blregist" />
            </a-form-item>
            <a-form-item label="说明" name="bldescription">
                <a-textarea :disabled="canEdit" v-model:value.trim="form.bldescription" placeholder="请输入说明"
                    :auto-size="{ minRows: 2, maxRows: 5 }" />
            </a-form-item>
            <a-form-item label="管理办法上传" name="bldescription" v-show="!canEdit">
                <a-upload accept=".pdf,.docx,.doc" v-model:file-list="fileListTwo" name="file" :multiple="true"
                    :before-upload="beforeUpload" :customRequest="customRequestTwo" :headers="headers"
                    @change="handleChangeOne">
                    <a-button :disabled="canEdit">
                        <upload-outlined></upload-outlined>
                        点击上传
                    </a-button>
                </a-upload>
            </a-form-item>
            <a-form-item label="管理办法展示" name="bldescription" v-show="canEdit || form.blprojectid">
                <a-list item-layout="horizontal" :data-source="typeTwoArray">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <a-list-item-meta>
                                <template #title>
                                    <a :href="item.url" target="_blank" style="color: #1677ff;">{{ item.fileName }}</a>
                                </template>
                            </a-list-item-meta>
                            <template #actions>
                                <a key="list-loadmore-edit" v-show="!canEdit"
                                    @click=delFile(form.blprojectid,item,2)>删除</a>
                            </template>
                        </a-list-item>
                    </template>
                </a-list>
            </a-form-item>
            <a-form-item label="协议上传" name="bldescription" v-show="!canEdit">
                <a-upload accept=".pdf,.docx,.doc" v-model:file-list="fileListOne" name="file" :multiple="true"
                    :before-upload="beforeUpload" :customRequest="customRequestOne" :headers="headers"
                    @change="handleChangeTwo">
                    <a-button :disabled="canEdit">
                        <upload-outlined></upload-outlined>
                        点击上传
                    </a-button>
                </a-upload>
            </a-form-item>
            <a-form-item label="协议展示" name="bldescription" v-show="canEdit || form.blprojectid">
                <a-list item-layout="horizontal" :data-source="typeOneArray">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <a-list-item-meta>
                                <template #title>
                                    <a :href="item.url" target="_blank" style="color: #1677ff;">{{ item.fileName }}</a>
                                </template>
                            </a-list-item-meta>
                            <template #actions>
                                <a key="list-loadmore-edit" v-show="!canEdit"
                                    @click=delFile(form.blprojectid,item,1)>删除</a>
                            </template>
                        </a-list-item>
                    </template>
                </a-list>
            </a-form-item>
        </a-form>
        <template #footer>
            <a-space>
                <a-button @click="onClose" v-show="!canEdit">取消</a-button>
                <a-button type="primary" v-show="!canEdit" v-throttle @click="onSubmit">保存</a-button>
            </a-space>
        </template>
    </a-modal>
</template>

<script setup>
    import { message, Modal } from 'ant-design-vue';
    import pcaa from 'china-area-data';
    import _ from 'lodash';
    import { nextTick, reactive, ref, defineProps, onMounted, computed, watchEffect, watch } from 'vue';
    import { ProNameApi } from '/@/api/basicManage/Promanage/ProName-api';
    import { employeeApi } from '/src/api/system/employee-api';
    import { ProLeaderApi } from '/src/api/basicManage/DonationManage/ProLeader-api';
    import AreaCascader from '/@/components/framework/area-cascader/index.vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import Upload from '/@/components/support/file-upload/index.vue';
    import { regular } from '/@/constants/regular-const';
    import { useUserStore } from '/@/store/modules/system/user';
    import { smartSentry } from '/@/lib/smart-sentry';
    import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
    defineExpose({
        showModal,
        showViewModal
    });

    const emit = defineEmits(['refresh']);
    // ====== 标题===============
    const title = ref("");
    // 是否可编写
    const canEdit = ref(false);
    // 是否上传
    const isUpdate = ref(false)
    // --------------------- modal 显示与隐藏 ---------------------
    // 是否展示
    const visible = ref(false);

    function showModal(data) {
        Object.assign(form, formDefault);
        if (data.blprojectid && !_.isEmpty(data)) {
            Object.assign(form, data);
            if (data.blprojectstatus == 0) {
                form.blprojectstatus = "无"
            } else if (data.blprojectstatus == 1) {
                form.blprojectstatus = "未执行"
            } else if (data.blprojectstatus == 2) {
                form.blprojectstatus = "执行中"
            } else if (data.blprojectstatus == 3) {
                form.blprojectstatus = "待续约"
            } else {
                form.blprojectstatus = "结项"
            }
            getFile(data.blprojectid);
        }

        visible.value = true;
        nextTick(() => {
            formRef.value.clearValidate();
        });
        title.value = getTitle()
    }
    // ============查看modal =======
    function showViewModal(data) {
        Object.assign(form, formDefault);
        if (data.blprojectid && !_.isEmpty(data)) {
            Object.assign(form, data);
            if (data.blprojectstatus == 0) {
                form.blprojectstatus = "无"
            } else if (data.blprojectstatus == 1) {
                form.blprojectstatus = "未执行"
            } else if (data.blprojectstatus == 2) {
                form.blprojectstatus = "执行中"
            } else if (data.blprojectstatus == 3) {
                form.blprojectstatus = "待续约"
            } else {
                form.blprojectstatus = "结项"
            }
            // 项目联系人  项目负责人
            if (data.blprojectcontact == 1) {

            }

            getFile(data.blprojectid);
        }
        canEdit.value = true;
        visible.value = true;
        nextTick(() => {
            formRef.value.clearValidate();
        });
        title.value = getTitle()

    }

    // 查看管理办法  和 协议文件列表
    const typeOneArray = ref("");
    const typeTwoArray = ref("");
    // 获取文件  getFile  ProNameApi
    async function getFile(id) {
        try {
            let viewFile = await ProNameApi.getIdsFile(id);
            const viewFileList = viewFile.data.attachment
            const type1Array = viewFileList.filter(item => item.type === "1");
            typeOneArray.value = type1Array
            const type2Array = viewFileList.filter(item => item.type === "2");
            typeTwoArray.value = type2Array
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // ============== 删除文件 ===========
    const delFile = async (proid, fileid, type) => {

        Modal.confirm({
            title: '提示',
            content: '确定要删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                BatchDelete(proid, fileid.id);
            },
            cancelText: '取消',
            onCancel() { },
        });
    }
    async function BatchDelete(proid, id) {
        try {
            SmartLoading.show();
            let array = [id];
            await ProNameApi.delFile(array);
            message.success('删除成功');
            getFile(proid)
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }
    // ==================文件上传=============
    const fileListOne = ref([]);
    const fileListTwo = ref([]);
    const headers = {
        "Authorization": `Bearer ${useUserStore().getToken}`,
    };
    const beforeUpload = file => {
        return new Promise((resolve, reject) => {
            if (form.blprojectnum === null || form.blprojectnum === undefined || form.blprojectnum === '') {
                message.error('请上传文件前，先填写完整信息');
                return false
            }
            const fileType = file.name.replace(/.+\./, '');
            const fileFormat =
                fileType === 'pdf' ||
                fileType === 'docx' ||
                fileType === 'doc'
            const fileSize = file.size !== 0;

            if (!fileFormat) {
                message.error('只能上传pdf、docx和doc格式文件!');
                return false
            }
            const isLt2M = file.size / 1024 / 1024 < 100;
            if (!isLt2M) {
                message.error('图片尺寸不能超过100MB!');
                return false
            }
            if (!fileSize) {
                fileList.splice(fileList.indexOf(file), 1);
                message.error('不能上传空文件!');
                return false;
            }
            return resolve(true)
        });
    };
    const handleChangeOne = (info) => {
        let { fileList } = info
        const status = info.file.status
        if (status !== 'uploading') {
        }
        if (status === 'done') {
            fileListTwo.value.push({ uid: fileList[fileList.length - 1].uid, url: info.file.response.address })
        }
        fileListTwo.value = [...fileList]
    };
    const handleChangeTwo = (info) => {
        let { fileList } = info
        const status = info.file.status
        if (status !== 'uploading') {
        }
        if (status === 'done') {
            fileListOne.value.push({ uid: fileList[fileList.length - 1].uid, url: info.file.response.address })
        }
        fileListOne.value = [...fileList]
    };
    const customRequestTwo = async (options) => {
        SmartLoading.show();
        try {
            const formData = new FormData();
            formData.append('file', options.file);
            const params = {
                blProjectNum: form.blprojectnum,
                type: 2,
            }
            const dd = Object.keys(params)
                .map((key) => key + '=' + params[key])
                .join('&')
            let res = await ProNameApi.uploadFile(dd, formData);
            options.onSuccess(res, options.file);
            message.success(`上传成功`);
            if (form.blprojectid) {
                fileListTwo.value = []

                getFile(form.blprojectid);
            } else {
                fileListTwo.value = fileListTwo.value.filter(item => !item.url);

            }
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    };
    const customRequestOne = async (options) => {
        SmartLoading.show();
        try {
            const formData = new FormData();
            formData.append('file', options.file);
            const params = {
                blProjectNum: form.blprojectnum,
                type: 1,
            }
            const dd = Object.keys(params)
                .map((key) => key + '=' + params[key])
                .join('&')
            let res = await ProNameApi.uploadFile(dd, formData);
            options.onSuccess(res, options.file);
            message.success(`上传成功`);
            if (form.blprojectid) {
                fileListOne.value = []
                getFile(form.blprojectid);

            } else {
                fileListOne.value = fileListOne.value.filter(item => !item.url);
            }
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    };
    //鼠标悬停事件
    const handleMouseEnter = () => {
        showDeleteIcon.value = true;
    }
    //鼠标离开事件
    const handleMouseLeave = () => {
        showDeleteIcon.value = false;
    }
    //删除当前图片
    function handleRemove(file) {
    }

    // ============新增modal =======
    function getTitle() {
        let srt = ''
        if (!form.showView) {
            if (form.blprojectid) {
                srt = '编辑'
            } else {
                srt = '新增'
            }
        } else {
            srt = '查看'
        }
        return srt
    }

    // --------------------- form 表单 ---------------------

    // 关闭弹框
    function onClose() {
        Object.assign(form, formDefault);

        delete form.showView;
        visible.value = false;
        canEdit.value = false;
    }
    // 邮箱正则
    const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

    // --------------------- 表单 ---------------------

    //  组件
    const formRef = ref();

    const formDefault = {
        blprojectid: undefined,
        blprojectname: undefined,//项目名称
        blprojectnum: undefined,//项目编号
        bldepartmentnum: undefined,//部门编号
        blprojectcontact: undefined,//项目联系人
        blprojectleader: undefined,//项目负责人
        blfinancialnum: undefined,//财务编号
        blprojectstatus: undefined,//项目状态
        blregist: undefined,//项目成立日期
        bldescription: '',//说明
    };
    let form = reactive({ ...formDefault });
    const rules = {
        blprojectname: [{ required: true, message: '请输入项目名称' }],
        blprojectnum: [{ required: true, message: '请输入部门编号' }],
        bldepartmentnum: [{ required: true, message: '请选择部门' }],
        blprojectcontact: [{ required: true, message: '请选择项目联系人' }],
        blprojectleader: [{ required: true, message: '请选择项目负责人' }],
        blfinancialnum: [{ required: true, message: '请输入财务编号' }],
        blprojectstatus: [{ required: true, message: '请选择项目状态' }],
        blregist: [{ required: true, message: '请选择项目成立日期' }],
        bldescription: [{ required: false, message: '请输入说明' }],
    };
    function onSubmit() {
        formRef.value
            .validate()
            .then(async () => {
                isUpdate.value = false;
                SmartLoading.show();
                try {
                    form.bldescription = form.bldescription
                    if (form.blprojectid) {
                        await ProNameApi.foundationUpdate(form);
                    } else {
                        await ProNameApi.foundationAdd(form);

                    }
                    message.success(`${form.blprojectid ? '修改' : '添加'}成功`);
                    emit('refresh');
                    onClose();
                } catch (error) {
                    smartSentry.captureError(error);
                } finally {
                    SmartLoading.hide();
                }
            })
            .catch((error) => {
                message.error('参数验证错误，请仔细填写表单数据!');
            });
    }
    // 改变项目状态
    const changeProStatus = (value) => {
        formDefault.blprojectstatus = value
    }
    // 执行单位选择
    const options = ref([])
    const onChangeDept = (value) => {
        formDefault.bldepartmentnum = value
    }
    // 项目联系人选择
    const optionsContact = ref([])
    const onChangeContact = (value, v) => {
        form.blprojectcontact = v.label
    }
    // 项目负责人选择
    const optionsLeader = ref([])
    const onChangeLeader = (value, v) => {
        form.blprojectleader = v.label
    }
    // departList  部门列表
    async function ajaxQuery() {
        try {
            let departList = await employeeApi.departList();
            const dataSource = departList.data
            options.value = dataSource.map(item => ({
                value: item.bldeptnum,
                label: item.blname
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 项目联系人  项目负责人
    async function ajaxQueryContact() {
        try {
            let departList = await ProLeaderApi.foundationNpList();
            const dataSource = departList.data
            optionsContact.value = dataSource.map(item => ({
                value: item.blleaderlistid,
                label: item.blleadername
            }));
            optionsLeader.value = dataSource.map(item => ({
                value: item.blleaderlistid,
                label: item.blleadername
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    onMounted(() => {
        ajaxQuery();
        ajaxQueryContact();
    })

</script>

<style lang="less" scoped>
    .form-width {
        width: 100% !important;
    }

    .footer {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }

    .ant-card-body {
        padding: 10px;
    }

    .ant-list .ant-list-item {
        padding: 6px 24px;
    }
</style>